import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { CmsArticleEntity } from '../entity/article';
import { CmsCategoryEntity } from '../entity/category';

/**
 * 描述
 */
@Provide()
export class CmsArticleService extends BaseService {
  @Inject()
  ctx;
  @InjectEntityModel(CmsArticleEntity)
  CmsArticleEntity: Repository<CmsArticleEntity>;
  @InjectEntityModel(CmsCategoryEntity)
  CmsCategoryEntity: Repository<CmsCategoryEntity>;

  /**
   * 重载新增接口
   */
  async add(param: any) {
    const { category_id } = param;
    if (category_id) {
      const category = await this.CmsCategoryEntity.findOne({
        where: { id: category_id },
      });
      category.arttcle_count = category.arttcle_count + 1;
      await this.CmsCategoryEntity.save(category);
    }
    return await super.add(param);
  }
  /**
   * 重载删除接口
   */
  async delete(ids: any) {
    for (const id of ids) {
      const article = await this.CmsArticleEntity.findOne({
        where: { id: id },
      });
      const category_id = article.category_id;
      if (category_id) {
        const category = await this.CmsCategoryEntity.findOne({
          where: { id: category_id },
        });
        if (!category) {
          continue;
        }
        if (category.arttcle_count > 0) {
          category.arttcle_count = category.arttcle_count - 1;
          await this.CmsCategoryEntity.save(category);
        }
      }
    }
    return await super.delete(ids);
  }
  /**
   * 重载分页接口
   */
  async page(query: any, option: any, connectionName?: any) {
    const originalUrl = this.ctx.originalUrl;
    const urlArr = originalUrl.split('/');
    const appName = urlArr[1];
    // 如果访问的是客户端，只返回状态为1的数据
    if (appName === 'app') {
      query.status = 1;
    }
    return await super.page(query, option, connectionName);
  }
  /**
   * 重载info接口
   */
  async info(id: any, infoIgnoreProperty?: string[]) {
    const result = await super.info(id, infoIgnoreProperty);
    const category_id = result.category_id;

    const originalUrl = this.ctx.originalUrl;
    const urlArr = originalUrl.split('/');
    const appName = urlArr[1];
    // 如果访问的是客户端，只返回状态为1的数据
    if (appName === 'app') {
      if (result.status != 1) {
        throw new CoolCommException('文章状态：未发布');
      }
      const category = await this.CmsCategoryEntity.findOne({
        where: { id: category_id },
      });
      result['category'] = category;
    }
    return result;
  }
  /**
   * 根据文章id获取上一篇/下一篇文章
   */
  async getAroundById(id: Number) {
    const article1 = await this.CmsArticleEntity.createQueryBuilder()
      .where('status = :status', { status: 1 })
      .andWhere('id < :id', { id: id })
      .orderBy('id', 'DESC')
      .getOne();
    const article2 = await this.CmsArticleEntity.createQueryBuilder()
      .where('status = :status', { status: 1 })
      .andWhere('id > :id', { id: id })
      .orderBy('id', 'ASC')
      .getOne();
    return {
      article1: article1 ? {
        id: article1.id,
        title: article1.title,
      } : null,
      article2: article2 ? {
        id: article2.id,
        title: article2.title,
      } : null,
    };
  }
}
